package cn.fintecher.pangolin.service.dataimp.task;

import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.elastic.BaseCase;
import cn.fintecher.pangolin.entity.elastic.Warning;
import cn.fintecher.pangolin.entity.elastic.WarningModel;
import cn.fintecher.pangolin.service.dataimp.elastic.BaseCaseElastic;
import cn.fintecher.pangolin.service.dataimp.model.ConfirmCommonModel;
import org.apache.commons.collections4.IterableUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 15:20 2019/11/5
 */

@Service("confirmWarningFuture")
public class ConfirmWarningFuture {
    @Autowired
    private BaseCaseElastic baseCaseElastic;

    /**
     * 多线程确认
     */
    @Async
    public CompletableFuture<List<Warning>> processWarning(List<WarningModel> list, UserModel userModel) {
        List<String> caseNumbers = new ArrayList<>();
        List<Warning> warnings = new ArrayList<>();
        for (WarningModel warningModel : list) {
            caseNumbers.add(warningModel.getCaseNumber());
        }
        BoolQueryBuilder builder = new BoolQueryBuilder();
        builder.must(QueryBuilders.termsQuery("caseNumber.keyword", caseNumbers));
        Iterable<BaseCase> iterable = baseCaseElastic.search(builder);
        List<BaseCase> baseCases = IterableUtils.toList(iterable);
        for (WarningModel warningModel : list) {
            Warning warning = new Warning();
            warning.setId(UUID.randomUUID().toString().replaceAll("-", "")); //主键ID
            warning.setCaseNumber(warningModel.getCaseNumber()); //案件编号
            warning.setBatchNumber(warningModel.getBatchNumber()); //批次号
            warning.setPrincipalName(warningModel.getPrincipalName()); //委托方名称
            warning.setPrincipalId(warningModel.getPrincipalId()); //委托方ID
            warning.setPersonalName(warningModel.getPersonalName()); //客户姓名
            warning.setCardNo(warningModel.getCardNo()); //卡号
            warning.setContent(warningModel.getContent()); //警告内容
            warning.setCertificateNo(warningModel.getCertificateNo()); //证件号
            for (BaseCase baseCase : baseCases) {
                if (warning.getCaseNumber().equals(baseCase.getCaseNumber())) {
                    warning.setCaseId(baseCase.getId());
                    break;
                }
            }
            warning.process(userModel.getId(), userModel.getRealName(), ZWDateUtil.getNowDateTime());
            warnings.add(warning);
        }
        return CompletableFuture.completedFuture(warnings);
    }
}
